package com.zjkj.mp.service.message.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zjkj.mp.dao.channel.ChannelDao;
import com.zjkj.mp.dao.message.MessageDao;
import com.zjkj.mp.dao.user.UserDao;
import com.zjkj.mp.service.finance.FinanceItemService;
import com.zjkj.mp.service.message.MessageService;
import com.zjkj.mp.utils.PaginatedResult;
import com.zjkj.mp.utils.Toolkit;
import com.zjkj.mp.utils.security.SpringSecurityUtils;
import com.zjkj.mp.vo.Logger;
import com.zjkj.mp.vo.channel.MpChannel;
import com.zjkj.mp.vo.message.Message;
import com.zjkj.mp.vo.message.MessageMx;
import com.zjkj.mp.vo.user.MpUser;

@Service
@Transactional(rollbackFor=Exception.class)
public class MessageServiceImpl implements MessageService {

	@Resource(name="messageDaoImpl")
	MessageDao messageDao;
	@Resource(name="channelDaoImpl")
	ChannelDao channelDao;
	@Resource
	Toolkit tool;
	@Autowired
	UserDao userDAO;
	@Autowired
	FinanceItemService financeItemService;

	public Message saveMessage(String sendInfo){
		//获取开始时间
		String startTime = tool.getSystemTime();
		String fsId = tool.getID();
		//记录发送短信
		Message message = new Message();
		message.setUserId(((MpUser)SpringSecurityUtils.getCurrentUser()).getUserId());
		message.setContent(sendInfo);
		message.setFsId(fsId);
		message.setSendDate(startTime);
		messageDao.insertMessage(message);
		return message;
	}
	
	public String sendMessage(String channel, String numbers, String sendInfo, Message message, long balance) {
		// 取得通道的详细信息
		int tdId = Integer.parseInt(channel);
		List<MpChannel> channelList = channelDao.getMpChannelList(tdId);
		MpChannel mpChannel = null;
		String tdmc = null;
		if(null==channelList||channelList.size()==0){
			//...
		}else{
			mpChannel = channelList.get(0);
			tdmc = mpChannel.getTdmc();
		}
		// 开始发送
		String fs_msg = null;
		if(!"".equals(tdmc) || null != tdmc){
			Map<String, Object> map = new HashMap<String, Object>();
			String[] str = numbers.split(",");
			for (int i = 0; i < str.length; i++) {
				map = sendMessageToZgwd(mpChannel, str[i], sendInfo);
				//map.put("signMsg","1");
				//map.put("msg", "发送短信1条");
				//记录短信明细
				MessageMx mx = new MessageMx();
				mx.setFsId(message.getFsId());
				mx.setMxId(tool.getID());
				mx.setNote((String)map.get("msg"));
				mx.setPhoneNumber(Double.parseDouble(str[i]));
				mx.setState((String)map.get("signMsg"));
				messageDao.insertMessageMx(mx);
			}
			//判断明细表是否全部发送成功
			int count = messageDao.searchMessageCount(message.getFsId());
			//扣除发送成功的短信数
			long totalCount = balance - count;
			messageDao.updateMessageCount(totalCount, message.getUserId());
			//获取结束时间
			String endTime = tool.getSystemTime();
			message.setEndDate(endTime);
			message.setTotalCount(count);
			if(count==str.length){
				fs_msg = "发送成功";
				message.setState(fs_msg);
			}else{
				fs_msg = "发送失败";
				message.setState(fs_msg);
			}
			messageDao.updateMessage(message);
		}else{
			fs_msg = "请选择正确通道";
		}
 
		//插入一条财务明细,记录发送短信
		this.financeItemService.sendMessage(1);
		
		return fs_msg; 
	}
	
	public void saveLogger(String fs_msg){
		// 记录发送操作日志
		Logger logger = new Logger();
		logger.setLogId(tool.getID());
		logger.setLognr(fs_msg);
		logger.setLogtime(tool.getSystemTime());
		logger.setLogUser(SpringSecurityUtils.getCurrentUserName());
		messageDao.insertLogger(logger);
	}
	
	public Map<String, Object> sendMessageToZgwd(MpChannel mpChannel, String phoneNumber, 
			String sendInfo) {
		String fsdxdz = mpChannel.getFsdxdz();
		//用户名、密码、手机号、发送信息
		String dxcslb = mpChannel.getDxcslb();
		//返回结果信息
		String msg = "";
		//返回结果状态
		String signMsg = "";
		//进行消息发送操作,http传递参数列表值
		String[] cslb = dxcslb.split(",");
		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(fsdxdz);
		post.addRequestHeader("Content-Type",
				"application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码
		NameValuePair[] data = { new NameValuePair(cslb[0], cslb[4]),
				new NameValuePair(cslb[1], cslb[5]),
				new NameValuePair(cslb[2], phoneNumber),
				new NameValuePair(cslb[3], sendInfo) };
		post.setRequestBody(data);

		try {
			client.executeMethod(post);
			Header[] headers = post.getResponseHeaders();
			int statusCode = post.getStatusCode();
			System.out.println("statusCode:" + statusCode);
			for (Header h : headers) {
				System.out.println(h.toString());
			}
			signMsg = new String(post.getResponseBodyAsString().getBytes(
					"gbk"));
			System.out.println(signMsg);
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		/**
		 * 短信发送后返回值   说明
		 * -1   没有该用户账户
		 * -2   密钥不正确 [查看密钥]
		 * -3   短信数量不足
		 * -11 该用户被禁用
		 * -14 短信内容出现非法字符
		 * -4   手机号格式不正确
		 * -41 手机号码为空
		 * -42 短信内容为空
		 * 大于0  短信发送数量
		 */
		post.releaseConnection();
		Map<String, Object> map = new HashMap<String, Object>();
		if (signMsg.equals("-1")) {
			msg = "没有该用户账户";
		}
		if (signMsg.equals("-2")) {
			msg = "密钥不正确";
		}
		if (signMsg.equals("-3")) {
			msg = "短信数量不足";
		}
		if (signMsg.equals("-11")) {
			msg = "该用户被禁用";
		}
		if (signMsg.equals("-14")) {
			msg = "短信内容出现非法字符";
		}
		if (signMsg.equals("-4")) {
			msg = "手机号格式不正确";
		}
		if (signMsg.equals("-41")) {
			msg = "手机号码为空";
		}
		if (signMsg.equals("-42")) {
			msg = "短信内容为空";
		}
		if (Integer.parseInt(signMsg)>0) {
			msg = "发送信息"+signMsg+"条";
		}
		map.put("msg", msg);
		map.put("signMsg", signMsg);
		return map;
	}

	@Override
	public PaginatedResult getMessageList(int pageNo, int pageSize,
			Map<String, Object> params) {
		if(params == null) params = new HashMap<String, Object>();		
		return this.messageDao.getList(pageNo, pageSize, params);
	}

	@Override
	public void updateMessageState(String fsId, String newState) {
		 this.messageDao.updateMessageState(fsId, newState);
	}

}